import { getUserInfo, getUserPhoto, login } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import {resetRouter} from '@/router/index'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    // 存token
    setToken(state, payload) {
      state.token = payload
      setToken(payload)
    },
    // 删token
    delToken(state) {
      state.token = ''
      removeToken()
    },
    // 存用户资料
    setUserInfo(state, payload) {
      state.userInfo = payload
    },
    // 删用户资料
    delUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 删用户信息和token
    logout(context) {
      context.commit('delToken')
      context.commit('delUserInfo')
      // 重置路由
      resetRouter()
    },
    async userLogin(context, payload) {
      const { data } = await login(payload)
      context.commit('setToken', data.data)
    },
    async userInfo(context) {
      const { data } = await getUserInfo()
      // console.log(data.data)
      const photo = await getUserPhoto(data.data.userId)
      // console.log(photo.data.data)
      context.commit('setUserInfo', { ...data.data, ...photo.data.data })
      return data.data.roles.menus
    }
  }
}
